using System;
using System.Collections.Generic;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using TenantManagementService.Monitoring;

namespace TenantManagementService.Monitoring
{
    /// <summary>
    /// 告警记录实体
    /// </summary>
    public class Alert : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 告警规则ID
        /// </summary>
        public virtual Guid AlertRuleId { get; protected set; }

        /// <summary>
        /// 告警级别
        /// </summary>
        public virtual AlertLevel Level { get; protected set; }

        /// <summary>
        /// 告警状态
        /// </summary>
        public virtual AlertStatus Status { get; protected set; } = AlertStatus.Active;

        /// <summary>
        /// 告警标题
        /// </summary>
        public virtual string Title { get; protected set; } = string.Empty;

        /// <summary>
        /// 告警消息
        /// </summary>
        public virtual string Message { get; protected set; } = string.Empty;

        /// <summary>
        /// 触发时的指标值
        /// </summary>
        public virtual decimal TriggeredValue { get; protected set; }

        /// <summary>
        /// 维度（JSON格式）
        /// </summary>
        public virtual string? Dimensions { get; protected set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public virtual DateTime StartTime { get; protected set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public virtual DateTime? EndTime { get; protected set; }

        /// <summary>
        /// 持续时间（秒）
        /// </summary>
        public virtual int Duration => EndTime.HasValue ? (int)(EndTime.Value - StartTime).TotalSeconds : (int)(DateTime.Now - StartTime).TotalSeconds;

        /// <summary>
        /// 是否已通知
        /// </summary>
        public virtual bool IsNotified { get; protected set; } = false;

        /// <summary>
        /// 最后通知时间
        /// </summary>
        public virtual DateTime? LastNotificationTime { get; protected set; }

        /// <summary>
        /// 通知次数
        /// </summary>
        public virtual int NotificationCount { get; protected set; } = 0;

        /// <summary>
        /// 处理人
        /// </summary>
        public virtual string? Assignee { get; protected set; }

        /// <summary>
        /// 处理时间
        /// </summary>
        public virtual DateTime? HandledTime { get; protected set; }

        /// <summary>
        /// 处理备注
        /// </summary>
        public virtual string? HandleNote { get; protected set; }

        /// <summary>
        /// 告警标签（JSON格式）
        /// </summary>
        public virtual string? Tags { get; protected set; }

        protected Alert() { }

        public Alert(
            Guid id,
            Guid alertRuleId,
            AlertLevel level,
            string title,
            string message,
            decimal triggeredValue,
            Dictionary<string, string>? dimensions = null,
            Guid? tenantId = null) : base(id)
        {
            AlertRuleId = alertRuleId;
            Level = level;
            Title = Check.NotNullOrWhiteSpace(title, nameof(title), maxLength: 500);
            Message = Check.NotNullOrWhiteSpace(message, nameof(message), maxLength: 2000);
            TriggeredValue = triggeredValue;
            Dimensions = dimensions != null && dimensions.Count > 0 ?
                System.Text.Json.JsonSerializer.Serialize(dimensions) : null;
            TenantId = tenantId;
            Status = AlertStatus.Active;
            StartTime = DateTime.Now;
        }

        /// <summary>
        /// 解决告警
        /// </summary>
        public virtual Alert Resolve(string? handleNote = null)
        {
            if (Status == AlertStatus.Resolved)
            {
                return this;
            }

            Status = AlertStatus.Resolved;
            EndTime = DateTime.Now;
            HandleNote = handleNote;
            return this;
        }

        /// <summary>
        /// 忽略告警
        /// </summary>
        public virtual Alert Ignore(string? handleNote = null)
        {
            if (Status == AlertStatus.Ignored)
            {
                return this;
            }

            Status = AlertStatus.Ignored;
            EndTime = DateTime.Now;
            HandleNote = handleNote;
            return this;
        }

        /// <summary>
        /// 分配告警
        /// </summary>
        public virtual Alert Assign(string assignee)
        {
            Assignee = Check.NotNullOrWhiteSpace(assignee, nameof(assignee));
            return this;
        }

        /// <summary>
        /// 处理告警
        /// </summary>
        public virtual Alert Handle(string assignee, string handleNote)
        {
            Assignee = Check.NotNullOrWhiteSpace(assignee, nameof(assignee));
            HandleNote = Check.NotNullOrWhiteSpace(handleNote, nameof(handleNote));
            HandledTime = DateTime.Now;
            return this;
        }

        /// <summary>
        /// 标记已通知
        /// </summary>
        public virtual Alert MarkAsNotified()
        {
            IsNotified = true;
            LastNotificationTime = DateTime.Now;
            NotificationCount++;
            return this;
        }

        /// <summary>
        /// 获取维度字典
        /// </summary>
        public virtual Dictionary<string, string>? GetDimensions()
        {
            if (string.IsNullOrWhiteSpace(Dimensions))
            {
                return null;
            }

            try
            {
                return System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(Dimensions);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取标签
        /// </summary>
        public virtual Dictionary<string, string>? GetTags()
        {
            if (string.IsNullOrWhiteSpace(Tags))
            {
                return null;
            }

            try
            {
                return System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(Tags);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 设置标签
        /// </summary>
        public virtual Alert SetTags(Dictionary<string, string>? tags)
        {
            Tags = tags != null && tags.Count > 0 ?
                System.Text.Json.JsonSerializer.Serialize(tags) : null;
            return this;
        }

        /// <summary>
        /// 检查告警是否活跃
        /// </summary>
        public virtual bool IsActive()
        {
            return Status == AlertStatus.Active;
        }

        /// <summary>
        /// 检查是否需要重新通知
        /// </summary>
        public virtual bool NeedsRenotification(int intervalHours = 4)
        {
            if (!IsNotified)
            {
                return true;
            }

            return LastNotificationTime.HasValue &&
                   DateTime.Now.Subtract(LastNotificationTime.Value).TotalHours >= intervalHours;
        }
    }
}